<template>
	<view class="image-viewer-container">
		<!-- 图片轮播组件 -->
		<swiper 
			class="image-swiper" 
			:indicator-dots="true" 
			:autoplay="false" 
			:interval="3000" 
			:duration="500"
			:current="currentIndex"
			@change="onSwiperChange">
			<swiper-item v-for="(image, index) in imageList" :key="index">
				<image 
					:src="image" 
					class="swiper-image" 
					mode="aspectFit"
					@error="onImageError"
					@load="onImageLoad">
				</image>
			</swiper-item>
		</swiper>
		
		<!-- 图片加载状态覆盖层 -->
		<view v-if="imageLoading" class="loading-overlay">
			<view class="loading-content">
				<text class="loading-text">图片加载中...</text>
			</view>
		</view>
		
		<!-- 图片错误状态覆盖层 -->
		<view v-if="imageError" class="error-overlay">
			<view class="error-content">
				<text class="error-text">图片加载失败，请检查网络连接</text>
				<view class="error-back-btn" @tap="goBack">
					<text class="error-back-text">返回</text>
				</view>
			</view>
		</view>
		
		<!-- UI覆盖层 -->
		<view class="overlay-ui">
			<!-- 顶部栏 -->
			<view class="top-bar" :style="{paddingTop: statusBarHeight + 'px'}">
				<view class="left-content">
					<text class="back-btn" @tap="goBack">‹</text>
					<text class="title">{{ bookName }}</text>
				</view>
				<view class="right-content">
					<text class="collect-btn" @tap="toggleCollect" :class="{collected: isCollected}">{{ isCollected ? '♥' : '♡' }}</text>
					<text class="page-indicator">{{ currentIndex + 1 }} / {{ imageList.length }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import * as BookRecordApi from '@/api/bookRecord.js';
	import * as BookApi from '@/api/book.js';

	export default {
		data() {
			return {
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				currentIndex: 0,
				imageLoading: false,
				imageError: false,
				bookName: '',
				bookId: null,
				isCollected: false,
				imageList: [
					'/static/url/defualt_1.png',
					'/static/url/defualt_2.png'
				]
			};
		},
		onLoad(options) {
			// 获取传递的参数
			this.bookName = options.bookName ? decodeURIComponent(options.bookName) : '图片查看器';
			this.bookId = options.bookId || null;
		
			this.isCollectBook(this.bookId);
			// 处理图片URL列表
			if (options.images) {
				try {
					const decodedImages = decodeURIComponent(options.images);
					let imageList = JSON.parse(decodedImages);
					// 处理图片路径，确保正确拼接静态资源路径
					this.imageList = imageList.map(url => {
						if (url && url.trim() !== '') {
							// 如果已经是完整路径，直接返回
							if (url.startsWith('/static/url/')) {
								return url;
							}
							// 如果包含错误前缀，提取图片名称并拼接正确路径
							if (url.includes('__pageframe__/pages/video/')) {
								let imageName = url.replace(/.*__pageframe__\/pages\/video\//, '');
								return `/static/url/${imageName}`;
							}
							// 如果是纯图片名称，拼接路径
							return `/static/url/${url}`;
						}
						return '/static/url/defualt_1.png';
					});
				} catch (e) {
					console.error('解析图片列表失败:', e);
				}
			} else if (options.url && options.url !== '') {
				// 处理图片URL（从书籍详情页跳转，可能是逗号分隔的多个图片名称）
				try {
					let decodedUrl = decodeURIComponent(options.url);
					if (decodedUrl && decodedUrl.trim() !== '') {
						// 按逗号分隔图片名称
						let imageNames = decodedUrl.split(',').map(name => name.trim()).filter(name => name !== '');
						
						// 处理每个图片名称
						this.imageList = imageNames.map(imageName => {
							// 如果已经是完整路径，直接使用
							if (imageName.startsWith('/static/url/')) {
								return imageName;
							} else if (imageName.includes('__pageframe__/pages/video/')) {
								// 提取图片名称并拼接正确路径
								let cleanName = imageName.replace(/.*__pageframe__\/pages\/video\//, '');
								return `/static/url/${cleanName}`;
							} else {
								// 如果是纯图片名称，拼接路径
								return `/static/url/${imageName}`;
							}
						});
					}
				} catch (e) {
					console.error('解析图片URL失败:', e);
				}
			}
			
			console.log('图片查看器页面参数:', {
				bookName: this.bookName,
				bookId: this.bookId,
				isCollected: this.isCollected,
				imageList: this.imageList
			});
			
			// 创建阅读记录
			if (this.bookId && this.bookName) {
				this.createReadingRecord();
			}
		},
		methods: {
			
			async isCollectBook(bookId){
			 const resp = await BookApi.isCollectBook(bookId)
				this.isCollected = resp.data
				console.log("isCollectBook1"+resp.data)
				console.log("isCollectBook2"+this.isCollected)
			},
			
			onSwiperChange(e) {
				this.currentIndex = e.detail.current;
			},
			onImageLoad() {
				this.imageLoading = false;
				this.imageError = false;
			},
			onImageError(e) {
				console.error('图片加载错误:', e);
				this.imageError = true;
				this.imageLoading = false;
				uni.showToast({
					title: '图片加载失败',
					icon: 'none'
				});
			},
			goBack() {
				uni.navigateBack();
			},
			// 创建阅读记录
			async createReadingRecord() {
				try {
					const params = {
						bookId: this.bookId,
						bookName: this.bookName
					};
					
					console.log('创建阅读记录参数:', params);
					
					const response = await BookRecordApi.createBookRecord(params);
					console.log('阅读记录创建成功:', response);
				} catch (error) {
					console.error('创建阅读记录失败:', error);
				}
			},
			// 切换收藏状态
			async toggleCollect() {
				if (!this.bookId) {
					uni.showToast({
						title: '书籍ID不存在',
						icon: 'none'
					});
					return;
				}
				
				try {
					const newCollectStatus = !this.isCollected;
					
					console.log('切换收藏状态:', {
						bookId: this.bookId,
						isCollect: newCollectStatus
					});
					
					const response = await BookApi.updateBookCollect(this.bookId.trim(), newCollectStatus);
					
					if (response.code === 200 || response.code === 0) {
						this.isCollected = newCollectStatus;
						uni.showToast({
							title: newCollectStatus ? '收藏成功' : '取消收藏',
							icon: 'success'
						});
						console.log('收藏状态更新成功:', response);
					} else {
						uni.showToast({
							title: response.msg || '操作失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('切换收藏状态失败:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style lang="scss">
	.image-viewer-container {
		width: 100vw;
		height: 100vh;
		position: relative;
		background-color: #000;
	}

	.image-swiper {
		width: 100%;
		height: 100%;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
	}

	.overlay-ui {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		pointer-events: none;
		z-index: 100;
	}

	.top-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20px;
		height: 60px;
		background: linear-gradient(to bottom, rgba(0,0,0,0.7), transparent);
		pointer-events: auto;
	}

	.left-content, .right-content {
		display: flex;
		align-items: center;
	}

	.back-btn {
		font-size: 24px;
		color: #fff;
		margin-right: 15px;
		padding: 10px;
		margin: -10px 5px -10px -10px;
		border-radius: 50%;
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(1.2);
			background-color: rgba(255, 255, 255, 0.2);
		}
	}

	.title {
		font-size: 16px;
		color: #fff;
		font-weight: 500;
	}

	.collect-btn {
		font-size: 20px;
		color: #fff;
		margin-right: 50px;
		padding: 5px;
		border-radius: 50%;
		transition: all 0.3s ease;
		
		&.collected {
			color: #ff6b9d;
			text-shadow: 0 0 10px rgba(255, 107, 157, 0.5);
		}
		
		&:active {
			transform: scale(1.2);
		}
	}

	.page-indicator {
		font-size: 14px;
		color: #fff;
		background-color: rgba(0, 0, 0, 0.5);
		padding: 4px 8px;
		border-radius: 12px;
	}

	.loading-overlay, .error-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgba(0, 0, 0, 0.8);
		z-index: 1000;
	}

	.loading-content, .error-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #fff;
	}

	.loading-text, .error-text {
		font-size: 16px;
		text-align: center;
	}
	
	.error-back-btn {
		margin-top: 20px;
		padding: 12px 24px;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 25px;
		border: 1px solid rgba(255, 255, 255, 0.3);
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(0.95);
			background-color: rgba(255, 255, 255, 0.3);
		}
	}
	
	.error-back-text {
		font-size: 16px;
		color: #fff;
		font-weight: 500;
	}
</style>